<script setup lang="ts">
import { encoder } from '/@/api/services/WaterMark'
import UploadItem from './uploadItem.vue'
import { ElMessage } from 'element-plus'
import vueEasyPrint from 'vue-easy-print'

// 加密
let format1 = ['jpg', 'jpeg', 'png']
let format2 = ['py', 'txt']
let has_file = ref<boolean>(false)
let file1 = ref<any>({})
let file2 = ref<any>({})
let modal1 = ref<boolean>(false)
let isCollapsed = ref<boolean>(false)
let formItem = ref<any>({})
let BASE_URL = import.meta.env.VITE_APP_API_BASE_URL + '/static/'
let imgFile = ref<any>(null)
let pyFile = ref<any>(null)
let returnedImgLink = ref<string>('')
let originImageLink = ref<string>('')
let psnr = ref<number>(1231)
let ssim = ref<number>(98.54)
let loadingStatus = ref<boolean>(false)
let current = ref<number>(0)


console.log(import.meta.env.VITE_APP_API_BASE_URL)

let pyHandleUpload = (py: any) => {
  // if (!/\.(py|txt)$/.test(py.name)) {
  //   handleFormatError(py, 'txt,py')
  //   return false
  // }
  // if (py.size > 1024 * 5) {
  //   handleMaxSize(py, '5kb')
  //   return false
  // }
  console.log(py)
  pyFile.value = py
  // file2.value = {
  //   size: (pyFile.size / 1024).toFixed(2) + 'kb',
  //   name: pyFile.name,
  //   type: pyFile.type,
  // }
  // has_file.value = true
  return false
}
// 处理图片上传
let imgHandleUpload = (file: File) => {
  // 验证图片格式
  if (!/\.(jpg|jpeg|png)$/.test(file.name)) {
    handleFormatError(file, 'jpg,png')
    return false
  }
  if (file.size > 1024 * 200) {
    handleMaxSize(file, '200kb')
    return false
  }
  imgFile.value = file
  file1 = {
    size: (imgFile.size / 1024).toFixed(2) + 'kb',
    name: imgFile.name,
    type: imgFile.type,
  }
  has_file.value = true
  return false
}
let closeimg = () => {
  imgFile = null
}
let closepy = () => {
  pyFile = null
}

let upload = () => {
  console.log('点击上传')
  console.log(imgFile.value)
  console.log(pyFile.value)

  if (!imgFile.value) {
    ElMessage({
      type: 'error',
      // title: '请上传图片',
      message: '加密需要图片和加密信息才能加密 ',
    })
    return
  }
  if (!pyFile.value) {
    ElMessage.error({
      // title: '请上传加密信息',
      message: '加密需要图片和加密信息才能加密 ',
    })
    return
  }

  loadingStatus.value = true
  encoder(imgFile.value, pyFile.value)
    .then(result => {
      loadingStatus.value = false
      imgFile.value = null
      pyFile.value = null
      modal1.value = true
      console.log(result)
      returnedImgLink.value = BASE_URL + result.watermarked_image_path
      originImageLink.value = BASE_URL + result.origin_image_path
      // let psnr = result.psnr + ''
      // psnr = psnr.substring(0, psnr.indexOf('.') + 3)
      // let ssim = result.ssim + ''
      // ssim = ssim.substring(0, ssim.indexOf('.') + 3)
    })
    .catch(error => {
      loadingStatus.value = false
      console.log(error)
      ElMessage.error({
        // title: '请上传加密信息',
        message: error,
      })
    })
}
let getUrlname = (url: string) => {
  //假如传进来的url是 http://www.qq.com/index.html?name=joey 这里一共是有3个斜杠,如果我们想获取index.html
  url = url.split('?')[0] // 我们只要?号前的
  let urlSlashCount = url.split('/').length // 统计有3斜杠
  return url.split('/')[urlSlashCount - 1].toLowerCase() //获取数组最后一个
}
const easyPrint = ref<any>([])
let dayin = () => {
  easyPrint.value.print()
  console.log('dayin')
}

// import { ComponentPublicInstance, HTMLAttributes } from "vue";
// const easyPrint = ref<HTMLElement | ComponentPublicInstance | HTMLAttributes>()


let download = () => {
  // console.log("下载")
  let image = new Image()
  let name = getUrlname(returnedImgLink.value)
  image.setAttribute('crossOrigin', 'anonymous')
  image.onload = function() {
    let canvas = document.createElement('canvas')
    canvas.width = image.width
    canvas.height = image.height
    let context = canvas.getContext('2d')
    context.drawImage(image, 0, 0, image.width, image.height)
    let url = canvas.toDataURL('image/jpeg') //得到图片的base64编码数据
    let a = document.createElement('a') // 生成一个a元素
    let event = new MouseEvent('click') // 创建一个单击事件
    a.download = name || 'photo' // 设置图片名称
    a.href = url // 将生成的URL设置为a.href属性
    a.dispatchEvent(event) // 触发a的单击事件
  }
  image.src = returnedImgLink.value
}

let handleFormatError = (file: any, desc: string) => {
  ElNotification.warning({
    title: '文件格式不正确',
    message:
      'File format of ' +
      file.name +
      ' is incorrect, please select ' +
      desc,
  })
}
let handleMaxSize = (file: any, desc: string) => {
  ElNotification.warning({
    title: '文件大小超出范围',
    message: 'File  ' + file.name + ' is too large, no more than ' + desc,
  })
}

</script>

<template>
  <div>
    <UploadItem
      v-if="!imgFile"
      :file="imgFile"
      :use-upload="true"
      step="step 1"
      name="请上传图片"
      :format="format1"
      @before-upload="imgHandleUpload"
    ></UploadItem>

    <UploadItem
      v-if="!pyFile"
      :file="pyFile"
      :use-upload="false"
      step="step 2"
      name="请上传文件"
      :format="format2"
      @bchange="pyHandleUpload"
    ></UploadItem>

    <div v-if="has_file">
      <ul class="onlineuploader-items-list">
        <li v-if="imgFile" class="onlineuploader-item">
          <el-row>
            <el-col :span="1">
              <div class="onlineuploader-item-image">
                <div class="image1"></div>
              </div>
            </el-col>
            <el-col :span="6" class="column-title">
              <div>{{ file1.name }}</div>
              <span>{{ file1.size }}</span>
            </el-col>
            <el-col :span="3" class="center">
              {{ file1.type }}
            </el-col>

            <el-col :span="1" :offset="13" @click="closeimg">
              <div class="wrong"></div>
            </el-col>
          </el-row>
        </li>
        <li v-if="pyFile" class="onlineuploader-item">
          <el-row>
            <el-col :span="1">
              <div class="onlineuploader-item-image">
                <div class="image2"></div>
              </div>
            </el-col>
            <el-col :span="6" class="column-title">
              <div>{{ file2.name }}</div>
              <span>{{ file2.size }}</span>
            </el-col>
            <el-col :span="3" class="center">
              {{ file2.type }}
            </el-col>
            <el-col :span="1" :offset="13" @click="closepy">
              <div class="wrong"></div>
            </el-col>
          </el-row>
        </li>
      </ul>
    </div>

    <el-row>
      <el-button class="up" @click="upload"> 点击上传</el-button>
    </el-row>

    <el-dialog
      v-model="modal1"
      draggable
      scrollable
      title="返回结果"
      ok-text="下载图片"
      @on-ok="download"
    >
      <!--      <el-descriptions :col="1">-->
      <!--        <el-descriptions-item term="PSNR：">-->
      <!--          {{ psnr }}-->
      <!--        </el-descriptions-item>-->
      <!--        <el-descriptions-item term="SSIM：">-->
      <!--          {{ ssim }}-->
      <!--        </el-descriptions-item>-->
      <!--      </el-descriptions>-->


      <el-descriptions :col="1" layout="vertical">
        <el-descriptions-item term="原图(左) 水印图(右): ">
          <el-row :gutter="4">
            <el-col :span="12">
              <img
                v-if="originImageLink"
                class="imgDisplay"
                :src="originImageLink"
                alt=""
              />
            </el-col>
            <el-col :span="12">
              <vue-easy-print tableShow ref="easyPrint">
                <img
                  v-if="returnedImgLink"
                  class="imgDisplay"
                  :src="returnedImgLink"
                  alt=""
                />
              </vue-easy-print>
            </el-col>
          </el-row>
        </el-descriptions-item>
      </el-descriptions>


      <el-row :gutter="4">
        <el-col :span="12">
          <el-button class="up" @click="download">下载</el-button>
        </el-col>
        <el-col :span="12">
          <el-button class="up" @click="dayin">打印</el-button>
        </el-col>
      </el-row>


    </el-dialog>
  </div>
</template>


<style type="css" scoped>
.lay {
  width: 100%;
}

.sideFont {
  color: #9ea7b4;
  font-size: 12px;
}

.upload {
  /*min-height: 130px;*/
  height: 100%;
}

.ivu-upload-drag {
  height: 100%;
  min-height: 130px !important;
}

.onlineuploader-items-list {
  display: block;
  margin: 0;
  padding: 0;
  list-style: none;
  /*border: 1px solid #ebeef1;*/
  cursor: pointer;
  box-shadow: 0 1px 2px 0 rgb(60 64 67 / 30%), 0 1px 3px 1px rgb(60 64 67 / 15%);
  border-radius: 0.625rem;
  border: 1px solid transparent;
  transition: box-shadow 0.4s, transform 0.4s;
}

.onlineuploader-items-list:hover {
  border: 1px solid #2b932f;
  transform: translateY(-2%);
}

.onlineuploader-item {
  position: relative;
  margin: 0;
  padding: 5px 16px 5px 22px;
  border-bottom: 1px solid #ebeef1;
  /*border-top: 1px solid #ebeef1;*/
}

.column-title {
  padding-left: 16px;
  padding-right: 16px;
  color: #555;
  overflow: hidden;
}

.column-title div {
  width: 100%;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  font-weight: 400;
  text-shadow: 0 1px 0 rgb(0 0 0 / 15%) !important;
}

.column-title span {
  font-size: 12px;
  color: #979fb8;
  opacity: 0.7;
  font-weight: 300;
}

.onlineuploader-item-image {
  display: flex;
  height: 100%;
  width: 100%;
}

.onlineuploader-item-image div {
  /*position: absolute;*/
  /*top: 0;*/
  /*left: 0;*/
  width: 32px;
  height: 32px;
  /*flex: 1;*/
  margin: auto;
  border-radius: 3px;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-position: center;
  /*box-shadow: 0 2px 5px 0 rgb(147 147 147 / 64%);*/
}

.image1 {
  background-image: url('../../assets/JPG_1.svg');
}

.image2 {
  background-image: url('../../assets/py.svg');
}

/*.up{*/
/*  width: 80%;*/
/*  margin: 20px auto;*/
/*}*/

.up {
  max-width: 300px;
  width: 300px;
  box-shadow: 0 0 0 0 rgb(232 76 61 / 70%);
  border-radius: 50px;
  background-color: #00944f;
  color: #fff;
  line-height: 44px;
  height: 44px;
  cursor: pointer;
  font-size: 20px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  padding: 0 20px;
  font-weight: 300;
  /*animation: PDFConvert 5s cubic-bezier(0.66, 0, 0, 1) infinite;*/
  animation-delay: 2s;
  text-align: center;
  margin: 20px auto 0;
}

.up:hover {
  animation: scale-out-click 0.4s;
}

.show_row {
  width: 100%;
}

.imgDisplay {
  height: 100%;
  width: 100%;
  /*max-height:150px;*/
  /*max-width:150px;*/
}

.wrong {
  background-image: url('../../assets/wrong.svg');
  background-repeat: no-repeat;
  background-size: 50% 50%;
  /*background-color: red;*/
  width: 100%;
  height: 100%;
  /*background: #259229;*/
  background-position: center;
}

.center {
  text-align: center;
  line-height: 100%;
  height: 100%;
}
</style>
